﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Globalization;

namespace XMLReportsImport
{
    class XMLSaleImport
    {
        private static void AddReportToDB(string xmlFile)
        {
            using (BookstoreDataClassesDataContext context = new BookstoreDataClassesDataContext())
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(xmlFile);
                XmlNode root = doc.DocumentElement;
                string datestring = root.Attributes["date"].Value;
                DateTime date = DateTime.ParseExact(
                    datestring, "dd/MM/yyyy", CultureInfo.InvariantCulture);
                
                string isbn;
                int amount;

                XmlNode store = root.FirstChild;
                foreach (XmlNode node in root.ChildNodes)
                {
                    string storeName = node.Attributes["store"].Value;
                    foreach (XmlNode saleNode in store.ChildNodes)
                    {
                        isbn = saleNode["isbn"].InnerText;
                        isbn = isbn.Replace("-", string.Empty);
                        amount = int.Parse(saleNode["amount"].InnerText);
                        AddSaleToDB(storeName, isbn, amount, date, context);
                    }
                    store = store.NextSibling;
                }
            }
        }

        private static void AddSaleToDB(string storeName, string isbn, int amount, DateTime date, BookstoreDataClassesDataContext context)
        {
            var book =
                from b in context.Books
                where b.ISBN == isbn
                select b;
            if (book.Count() == 0)
            {
                Console.WriteLine("Missing book");
                return;
            }
            var store =
                from s in context.Stores
                where s.Name == storeName
                select s;
            int storeId;
            if (store.Count() == 0)
            {
                Store st = new Store
                {
                    Name = storeName
                };
                context.Stores.InsertOnSubmit(st);
                context.SubmitChanges();
                storeId = st.StoreId;
            }
            else
            {
                storeId = store.First().StoreId;
            }
            Sale sale = new Sale
            {
                SaleDate = date,
                BookId = book.First().BookId,
                Amount = amount,
                StoreId = storeId
            };
            context.Sales.InsertOnSubmit(sale);
            context.SubmitChanges();
        }

        static void Main()
        {
            AddReportToDB("salesReport.xml");
        }
    }
}
